/*
 * Copyright 2009-2010 the original author or authors.
 *
 * Licensed under the Apache license, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.internna.iwebjtracker.mailer;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterReturning;
import org.internna.iwebmvc.utils.Assert;
import org.internna.iwebmvc.crypto.Cipherer;
import org.internna.iwebjtracker.issue.model.Issue;
import org.internna.iwebjtracker.issue.model.Comment;
import org.internna.iwebmvc.spring.util.RequestContextUtils;
import org.internna.iwebjtracker.javamail.server.JavamailServer;
import org.internna.iwebjtracker.spring.mvc.AccountActivationController;

/**
 * Sends mails when an intercepted operation is executed correctly.
 *
 * @author Jose Noheda
 */
@Aspect
public class MailerAspect {

    private static final Log logger = LogFactory.getLog(MailerAspect.class);

    private Cipherer cipherer;
    private final JavamailServer server;

    /**
     * Injects a required mail server.
     *
     * @param server a non null instance
     */
    public MailerAspect(JavamailServer server, Cipherer cipherer) {
        Assert.notNull(server);
        this.server = server;
        this.cipherer = cipherer;
    }

    /**
     * Sends an email given a successful user registration.
     *
     * @param retVal any (the result of the registration task)
     * @param username any
     * @param password any
     * @param email any
     * @throws MessagingException if the mail could not be created
     */
    @AfterReturning(pointcut = "execution(* org.internna.iwebjtracker.services.TrackerUserManager.register(..)) && args(username, password, email)", returning = "retVal")
    public void sendRegistrationMail(Object retVal, String username, String password, String email) throws MessagingException {
        if (retVal == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Sending activation email to [" + email + "] after successful user registration");
            }
            MimeMessage message = server.createMessage(email);
            message.setSubject("IWebJTracker registration");
            String url = RequestContextUtils.getApplicationUrl() + AccountActivationController.ACTIVATION_PATH + "?data=" + cipherer.encrypt(username + "#" + email);
            message.setContent("Hello " + username + ",<br/><br/>Welcome to IWebJTracker. Please confirm your email address by clicking <a href='" + url + "'>here</a> or browsing to " + url + " (you can copy&amp;paste the URL).<br/><br/>Greetings from the IWebJTracker team", "text/html");
            server.send(message);
        }
    }

    @AfterReturning(pointcut = "execution(* org.internna.iwebjtracker.services.IssueManager.comment(..)) && args(issue, comment, chat)", returning = "retVal")
    public void sendComment(Object retVal, Issue issue, Comment comment, String chat) {
        if (retVal == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Sending email to [" + issue.getAlias() + "] watchers after successful comment creation");
            }
        }
    }

}
